﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BlackStar;
using Microsoft.Xna.Framework.Input;

namespace BlackStarTest
{
    public class AppConsole
    {
        protected Component mainComponent;
        protected Textbox inputText;
        protected Label outputLabel;

        protected List<string> lines = new List<string>();

        public AppConsole(GUI g, string componentName)
        {
            mainComponent = g.FindComponent(componentName);
            inputText = (Textbox)mainComponent.FindComponent("ConsoleInput");
            outputLabel = (Label)mainComponent.FindComponent("ConsoleOutput");

            string[] starttext = outputLabel.Text.Split('\n');
            foreach (string s in starttext)
            {
                if( s.Trim() != string.Empty) lines.Add(s);
            }

            inputText.KeyDown += new ComponentKeyEvent(inputText_KeyDown);
            outputLabel.Resized += new ComponentEvent(outputLabel_Resized);
        }

        void outputLabel_Resized(Component sender)
        {
            outputLabel.Text = DisplayText();
        }

        void inputText_KeyDown(Component sender, Keys k)
        {
            switch(k)
            {
                case Keys.Enter:
                    AddLine(">" + sender.Text);
                    sender.Text = "";
                    break;
            }
        }

        public void AddLine(string value)
        {
            lines.Add(value);
            outputLabel.Text = DisplayText();
        }

        protected string DisplayText()
        {
            int fit = outputLabel.VisibleLines();

            string result = string.Empty;
            for (int i = 1; i <= fit && i <= lines.Count; i++)
            {
                result = " " + lines[lines.Count - i] + "\n" + result;
            }
            return result;
        }
    }
}
